package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    //前置处理
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //0.获取请求头 token
        String token = request.getHeader("Authorization");

        //1.判断令牌是否为空,为空返回401
        if (StrUtil.isBlank(token)) {
            response.sendError(401);
            return false;
        }

        //2.从redis中查询指定token,为空返回401
        String userJson = redisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);
        if (StrUtil.isBlank(userJson)) {
            response.sendError(401);
            return false;
        }

        //3.获取user
        User user = JSON.parseObject(userJson, User.class);

        //4.给token续期
        redisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN+token,userJson, Duration.ofDays(5));

        //5.将用户绑定到当前线程中
        UserHolder.set(user);
        return true;
    }

    @Override
    //渲染完成后处理
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //解绑线程中user
        UserHolder.remove();
    }
}
